<?php


namespace App\Repositories\Admin\User;


use App\Models\Permission;
use App\Repositories\BaseRepository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class PermissionRepository  extends BaseRepository
{

    public function model()
    {
        // TODO: Implement model() method.
        return new Permission();
    }
    public function create($data){
        $permission = $this->model();
        $permission->name = $data['name'];
        $permission->display_name = $data['display_name'];
        $permission->description = $data['description']??'';
        $permission->pid = $data['pid']??0;
        if($permission->pid!=0){
            //继承父级的顶级id
            $parent = $this->model()->find($permission->pid);
            if($parent->top_id==0){
                $permission->top_id = $parent->id;
            }else{
                $permission->top_id = $parent->top_id;
            }

        }
        return $permission->save()?$permission:[];
    }
    public function delete(Permission $permission){
        return DB::transaction(function ()use($permission){
            $children = $this->model()->where(['top_id'=>$permission->id])->first();
            if($children){
                $ChildDelete = $this->model()->where(['top_id'=>$permission->id])->delete();
                if(!$ChildDelete){
                    return false;
                }
            }
            $permission->delete();
            return true;
        });
    }
}
